package cn.globalph.housekeeper.widgets

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import kotlin.math.max
import kotlin.math.min

/**
 * 签字板
 */
class SignBoard : View {
    private lateinit var mPaint: Paint
    private var mPath: Path? = null
    private var mDownX = -1f
    private var mDownY = -1f
    private var mLastX = -1f
    private var mLastY = -1f

    private var mBufferCanvas:Canvas? = null
    private var mBufferBitmap:Bitmap? = null

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initData(context)
    }

    private fun initBuffer(){
        mBufferBitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888)
        mBufferCanvas = Canvas(mBufferBitmap!!)
    }

    private fun initData(context: Context) {
        mPaint = Paint()
        mPaint.color = 0xFF000000.toInt()
        mPaint.strokeWidth = 8f
        mPaint.style = Paint.Style.STROKE
        mPaint.isAntiAlias = true
        mPaint.strokeJoin = Paint.Join.ROUND
    }

    fun reSign(){
        mBufferBitmap?.eraseColor(Color.TRANSPARENT)
        mPath = null
        invalidate()
    }

    fun getBitmap():Bitmap?{
        return mBufferBitmap
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        event?.let {
            when (it.action) {
                MotionEvent.ACTION_DOWN -> {
                    mLastX = it.x
                    mLastY = it.y
                    if(mPath == null){
                        mPath = Path()
                    }
                    mPath?.moveTo(mLastX,mLastY)
                }
                MotionEvent.ACTION_UP,
                MotionEvent.ACTION_CANCEL,
                MotionEvent.ACTION_MOVE -> {
                    if(mBufferCanvas == null){
                        initBuffer()
                    }
                    mPath?.lineTo(it.x,it.y)
                    mBufferCanvas?.drawPath(mPath!!,mPaint)
                    var l = min(mLastX, it.x)
                    l = max(l-10,0f)
                    var r = max(mLastX,it.x)
                    r = min(r+10,width.toFloat())
                    var t = min(mLastY,it.y)
                    t = max(t-10,0f)
                    var b = max(mLastY,it.y)
                    b = min(b+10,height.toFloat())
                    postInvalidate(l.toInt(),t.toInt(),r.toInt(),b.toInt())
//                    invalidate()
                    mLastX = it.x
                    mLastY = it.y
                }
                else->{}
            }
        }
        return true
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        if(mBufferBitmap != null){
            canvas?.drawBitmap(mBufferBitmap!!,0f,0f,null)
        }
    }
}